//
// Created by francklinson on 2021/7/20 AT 19:42.
//
#include <vector>
#include <iostream>
#include <unordered_map>

using namespace std;

//Definition for a binary tree node.
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode() : val(0), left(nullptr), right(nullptr) {}

    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
private:
    unordered_map<TreeNode *, int> um; // 记忆化
    /**
     * 获得一个节点的深度
     * @param root
     * @return
     */
    int getDepth(TreeNode *root) {
        if (root == nullptr) return 0;
        if (um.count(root)) return um[root];
        int ans = 1 + max(getDepth(root->left), getDepth(root->right));
        um[root] = ans;
        return ans;
    }
public:
    /**
     * 主函数
     * @param root
     * @return
     */
    TreeNode *subtreeWithAllDeepest(TreeNode *root) {
        if (root == nullptr) return nullptr;
        auto leftDepth = getDepth(root->left);
        auto rightDepth = getDepth(root->right);
        if (leftDepth == rightDepth) return root;
        return leftDepth > rightDepth ? subtreeWithAllDeepest(root->left) : subtreeWithAllDeepest(root->right);
    }


};

int main() {
    auto n1 = TreeNode(3), n2 = TreeNode(5), n3 = TreeNode(1), n4 = TreeNode(6), n5 = TreeNode(2),
            n6 = TreeNode(0), n7 = TreeNode(8), n8 = TreeNode(7), n9 = TreeNode(4);
    n1.left = &n2;
    n1.right = &n3;
    n2.right = &n5;
    n3.left = &n6;
    n3.right = &n7;
    n5.left = &n8;
    n5.right = &n9;
    Solution solution;
    auto ans = solution.subtreeWithAllDeepest(&n1);
    cout << ans->val;
    return 0;
}

